import React, { useEffect, useState, useReducer } from 'react';
import clsx from 'clsx';
import { View, device, getLaunchOptionsSync, onDeviceInfoUpdated } from '@ray-js/ray';

import { useActions, useProps, useDevice } from '@ray-js/panel-sdk';
import { NavBar } from '@ray-js/smart-ui';
import debounce from 'lodash/debounce';

import * as Raw from '@/utils/raw';

import Header from '@/pages/home/componetns/Header';
import AromaCard from '@/pages/home/componetns/AromaCard';
import TimerCell from '@/pages/home/componetns/TimerCell';
import SectionCell from '@/pages/home/componetns/SectionCell';
import GearCell from '@/pages/home/componetns/GearCell';
import CycleCell from '@/pages/home/componetns/CycleCell';

import styles from './index.module.less';

type State = {
  timerSwitch: boolean;
  timerHour: number;
  startHour: number;
  startMinute: number;
  endHour: number;
  endMinute: number;
  startTime: number;
  pauseTime: number;
  gear: number;
};

type Action<K extends keyof State = keyof State> = {
  type: 'SET';
  key: K;
  value: State[K];
};

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'SET':
      return {
        ...state,
        [action.key]: action.value,
      };

    default:
      return state;
  }
}

const initialState: State = {
  timerSwitch: false,
  timerHour: 0,
  startHour: 0,
  startMinute: 0,
  endHour: 0,
  endMinute: 0,
  startTime: 10,
  pauseTime: 120,
  gear: 1,
};

export default function Home() {
  const { getDeviceInfo, registerDeviceListListener, onDeviceOnlineStatusUpdate } = device;
  const [state, dispatch] = useReducer(reducer, initialState);
  const power = useProps(props => props.switch); // 开关
  const battery = useProps(props => props.battery_percentage); // 电量
  const timer = useProps(props => props.timer); // 定时

  const timerCountDown = useProps(props => props.timer_count_down); // 定时剩余时间
  const aromaName = useProps(props => props.aroma_name); // 精油名称
  const work = useProps(props => props.work); // 工作状态
  const [deviceInfo, setDeviceInfo] = useState<any>({});

  // 设备信息
  const isOnline = deviceInfo?.isOnline as boolean; // 是否在线
  const network = useDevice(device => device.network.isConnected);
  const bluetooth = useDevice(device => device.bluetooth.available);
  const isConnected = isOnline && network && bluetooth; // 是否连接

  const actions = useActions();

  const [selectedDays, setSelectedDays] = useState<number[]>([]);

  useEffect(() => {
    const {
      query: { deviceId },
    } = getLaunchOptionsSync();

    getDeviceInfo({
      deviceId,
      success: info => {
        console.log('getDeviceInfo success', info);
        setDeviceInfo(info);
      },
    });
    registerDeviceListListener({ deviceIdList: [deviceId] });
    onDeviceOnlineStatusUpdate(env => {
      getDeviceInfo({
        deviceId,
        success: info => {
          setDeviceInfo(info);
        },
      });
    });

    onDeviceInfoUpdated(_ => {
      getDeviceInfo({
        deviceId,
        success: info => {
          setDeviceInfo(info);
        },
      });
    });
  }, []);

  useEffect(() => {
    if (timer) {
      const { isOn, hour } = Raw.parseTimingRaw(String(timer).trim());
      dispatch({ type: 'SET', key: 'timerSwitch', value: isOn });
      dispatch({ type: 'SET', key: 'timerHour', value: hour });
    }
    if (work) {
      const { startHour, startMinute, endHour, endMinute, days, startTime, pauseTime } =
        Raw.parseWorkRaw(work);
      dispatch({ type: 'SET', key: 'startHour', value: startHour });
      dispatch({ type: 'SET', key: 'startMinute', value: startMinute });
      dispatch({ type: 'SET', key: 'endHour', value: endHour });
      dispatch({ type: 'SET', key: 'endMinute', value: endMinute });
      dispatch({ type: 'SET', key: 'startTime', value: startTime });
      dispatch({ type: 'SET', key: 'pauseTime', value: pauseTime });
      const nextDays = days.map(day => (day === 7 ? 0 : day));
      setSelectedDays(nextDays);
    }
  }, [timer, work]);

  const toggleDay = debounce((index: number) => {
    const nextDays = selectedDays.includes(index)
      ? selectedDays.filter(i => i !== index)
      : [...new Set([...selectedDays, index])].sort((a, b) => a - b);
    setSelectedDays(nextDays);
    // 把0转换为7
    const nextDaysWith7 = nextDays.map(day => (day === 0 ? 7 : day));
    actions.work.set(
      Raw.generateWorkRaw(
        state.startHour,
        state.startMinute,
        state.endHour,
        state.endMinute,
        nextDaysWith7,
        state.startTime,
        state.pauseTime
      )
    );
  }, 500);

  // 处理工作参数下发
  const handleWork = debounce(
    (
      startHour: number,
      startMinute: number,
      endHour: number,
      endMinute: number,
      days: number[],
      startTime: number,
      pauseTime: number
    ) => {
      // 把0转换为7
      const nextDaysWith7 = days.map(day => (day === 0 ? 7 : day));
      actions.work.set(
        Raw.generateWorkRaw(
          startHour,
          startMinute,
          endHour,
          endMinute,
          nextDaysWith7,
          startTime,
          pauseTime
        )
      );
    },
    500
  );

  return (
    <>
      <NavBar
        title={deviceInfo.name}
        customStyle={{ backgroundColor: 'transparent' }}
        border={false}
      />
      <View className={styles.view}>
        <Header
          battery={battery}
          isOnline={deviceInfo?.isOnline}
          power={power}
          onPowerToggle={() => actions.switch.toggle()}
        />
        <View className={styles.content}>
          <AromaCard power={power} aromaName={aromaName} />
          <View
            className={clsx(styles.card, {
              [styles.disabled]: !power,
            })}
            style={{ gap: 10 }}
          >
            <TimerCell
              timerCountDown={timerCountDown}
              state={state}
              actions={actions}
              dispatch={dispatch}
            />
            <View className={styles.divider} />
            <SectionCell
              state={state}
              dispatch={dispatch}
              selectedDays={selectedDays}
              handleWork={handleWork}
            />
            <View className={styles.divider} />
            <GearCell
              state={state}
              dispatch={dispatch}
              selectedDays={selectedDays}
              handleWork={handleWork}
            />
            <View className={styles.divider} />
            <CycleCell
              timerSwitch={state.timerSwitch}
              selectedDays={selectedDays}
              toggleDay={toggleDay}
            />
          </View>
        </View>
      </View>
    </>
  );
}
